package SynchronizedStudy;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

//自己封装一个类,来保护共享资源-->Room就是共享的锁对象-->对共享资源进行保护
class Room{
    private int counter;//共享资源counter-->要对齐进行++,--操作
    //提供自增的方法对++操作进行保护
    public void increase(){
        synchronized (this){//给当前对象加锁-->当前对象为锁对象
            counter++;
        }
    }
    //提供自减方法对--操作进行保护
    public void decrease(){
        synchronized (this){//给当前对象加锁-->当前对象为锁对象
            counter--;
        }
    }
    //获取的时候,也需要加锁,为了保证获取的是准确地结果,而不是中间的结果
    public int getCounter() {
        synchronized(this){
            return counter;
        }
    }


}

public class IOPSynchronizedDemo {

    public static void main(String[] args) throws InterruptedException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS");
        String date = sdf.format(new Date());
        long num = (long) (Math.random() * (999L - 100L)) + 100L;
        System.out.println(date + num);
        Room room = new Room();//利用room对象(锁对象)来保护共享资源
        Thread t1 = new Thread(()->{
            for(int i =0;i<5000;++i){
                room.increase();
            }
        },"t1");

        Thread t2 = new Thread(()->{
            for(int i =0;i<5000;++i){
                room.decrease();
            }
        },"t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(room.getCounter());
    }
}

class Test{
    public synchronized static void test(){

    }
}



